<template>
  <div class="app-container flex">
    <JwChat-index
      v-model="inputMsg"
      scroll-type="noscroll"
      :config="config"
      :tale-list="list"
      :tool-config="toolConfig"
      @enter="bindEnter"
      @clickTalk="talkEvent"
    >
      <JwChat-rightbox :config="rightConfig" />
    </JwChat-index>
    <!--    <JwChat-talk :talelist="quickList" :config="quickConfig" @event="bindTalk" />-->
    <div style="width: 400px">
      <el-form label-width="80px">
        <el-form-item :label="$t('keyName')">
          <el-input v-model="workOrder.keyName" />
        </el-form-item>
        <el-form-item v-for="(item,index) in workOrder.describeList" :key="index" :label="item.name">
          <el-input v-model="item.value" />
        </el-form-item>
        <el-form-item :label="$t('problem')">
          <el-input
            v-model="workOrder.problem"
            type="textarea"
            :rows="8"
          />
        </el-form-item>
        <el-form-item :label="$t('enclosure')">
          <div v-for="(item ,index) in workOrder.enclosureList" :key="index" style="position: relative;width: 50%">
            <el-image
              style="width:100%;height: 120px"
              :src="item.downloadPath"
              :preview-src-list="[item.downloadPath]"
              fit="fit"
            />
            <el-button-group style="position: absolute;bottom: 10px;right: 5px">
              <el-button
                type="primary"
                icon="el-icon-download"
                @click="download(item)"
              />
            </el-button-group>
          </div>
        </el-form-item>
        <el-form-item :label="$t('enclosure')">
          <el-upload
            :headers="headers"
            drag
            :action="baseURL+'/erp/work/order/enclosure/uploadAndGet'"
            :on-success="handleSuccess"
            :on-error="handleError"
            :data="workOrder"
          >
            <i class="el-icon-upload" />
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getUserWithoutToken } from '@/api/auth/authUserApi'
import { getWorkOrder } from '@/api/erp/erpWorkOrderApi'
import { insertWorkOrderChat, pageGetWorkOrderChat } from '@/api/erp/erpWorkOrderChatApi'
import { formatDate } from '@/util/common'
import { getToken, getUserId } from '@/util/storage'
import { leaveWebSocket, listenWebSocket } from '@/util/websocketTool'

export default {
  name: 'WorkOrder',
  data() {
    return {
      baseURL: window.VUE_APP_BASE_API,
      headers: {
        'access-token': getToken()
      },
      userId: parseInt(getUserId()),
      currentPage: 1,
      createdUser: {},
      handleUser: {},
      workOrder: {},
      rightConfig: {
        listTip: '当前',
        list: []
      },
      toolConfig: {
        show: [], // 二级数组中放自定义名称
        showEmoji:
          true // 是否显示表情图标
      },
      list: [],
      inputMsg: '',
      config: {
        historyConfig: {
          show: true,
          tip: '滚动到顶时候显示的提示',
          callback: () => {
            this.currentPage = this.currentPage + 1
            this.pageGetWorkOrderChat()
          }
        }
      },
      wsMonitor: {
        room: 'erp:workOrder:' + this.workOrderId,

        onmessage: this.onSocketMsg
      }
      // quickConfig: {
      //   nav: ['快捷回复', '超级回复'],
      //   showAdd: true,
      //   maxlength: 200,
      //   showHeader: true,
      //   showDeleteBtn: true
      // },
      // quickList: [
      //   { text: '这里是jwchat，您想了解什么问题。' },
      //   { text: 'jwchat是最好的聊天组件' },
      //   { text: '谁将烟焚散，散了纵横的牵绊；听弦断，断那三千痴缠。' },
      //   { text: '长夏逝去。山野间的初秋悄然涉足。' },
      //   { text: '江南风骨，天水成碧，天教心愿与身违。' },
      //   { text: '总在不经意的年生。回首彼岸。纵然发现光景绵长。' },
      //   { text: '外面的烟花奋力的燃着，屋里的人激情的说着情话' },
      //   { text: '假如你是云，我就是雨，一生相伴，风风雨雨；' },
      //   { text: '即使泪水在眼中打转，我依旧可以笑的很美，这是你学不来的坚强。' },
      //   { text: ' 因为不知来生来世会不会遇到你，所以今生今世我会加倍爱你。' }
      // ],
    }
  }, created() {
    const param = this.$route.query
    this.workOrderId = param.workOrderId ? parseInt(param.workOrderId) : null
    // this.initSocket()
    this.getWorkOrder()
    this.wsMonitor.room = 'erp:workOrder:' + this.workOrderId
    listenWebSocket(this.wsMonitor)
  },
  beforeDestroy() {
    this.closeSocket()
  },
  methods: {
    handleError(err, file, fileList) {
      console.error(err)
      console.error(file)
      console.error(fileList)
    },
    handleSuccess(res, file, fileList) {
      this.getWorkOrder()
    },
    handlePictureCardPreview(file) {

    },
    download(item) {
      window.open(
        item.downloadPath
      )
    },
    closeSocket() {
      leaveWebSocket(this.wsMonitor)
      // if (this.ws) {
      //   this.ws.send(JSON.stringify({
      //     cmd: 'unBindRoom',
      //     param: 'erp:workOrder:' + this.workOrderId
      //   }))
      //   this.ws.onclose = null
      //   this.ws.close()
      //   this.ws = null
      // }
    },
    onSocketMsg(nowData) {
      if (nowData.type === 'workOrderChatInsert') {
        const item = JSON.parse(nowData.msg)
        const user = this.getUser(item.userId)
        const a = {
          'date': formatDate(this, item.createdDate),
          'text': { 'text': item.msg },
          'name': user.userName,
          'img': user.iconUrl
        }
        a.mine = this.userId === user.userId
        this.list.push(a)
      }
    },
    // initSocket() {
    //   const that = this
    //   this.closeSocket()
    //   this.ws = newWebSocket()
    //   this.ws.onopen = () => {
    //     that.ws.send(JSON.stringify({
    //       cmd: 'bindRoom',
    //       param: 'erp:workOrder:' + that.workOrderId
    //     }))
    //   }
    //   this.ws.onerror = function(e) {
    //     console.error('WebSocket is error' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.closeSocket()
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 20000)
    //   }
    //   this.ws.onclose = function(e) {
    //     console.error('WebSocket is close' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.closeSocket()
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 20000)
    //   }
    //   this.ws.onmessage = function(msg) {
    //     const nowData = JSON.parse(msg.data)
    //     if (nowData.type === 'workOrderChatInsert') {
    //       const item = JSON.parse(nowData.msg)
    //       const user = that.getUser(item.userId)
    //       const a = {
    //         'date': formatDate(that, item.createdDate),
    //         'text': { 'text': item.msg },
    //         'name': user.userName,
    //         'img': user.iconUrl
    //       }
    //       a.mine = that.userId === user.userId
    //       that.list.push(a)
    //     }
    //   }
    // },
    getWorkOrder() {
      getWorkOrder({
        workOrderId: this.workOrderId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.workOrder = data
          this.getHandleUserInfo()
          this.getCreatedUserInfo()
        }
      })
    },
    getHandleUserInfo() {
      getUserWithoutToken({
        userId: this.workOrder.handleUserId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.handleUser = data
          this.rightConfig.list.push({
            name: data.userName,
            'img': data.iconUrl
          })
          this.list = []
        }
      })
    },
    getCreatedUserInfo() {
      getUserWithoutToken({
        userId: this.workOrder.createdUserId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.createdUser = data
          this.rightConfig.list.push({
            name: data.userName,
            'img': data.iconUrl
          })
          this.pageGetWorkOrderChat()
        }
      })
    },
    toolEvent(type, obj) {
      console.log('tools', type, obj)
    },
    talkEvent(play) {
      console.log(play)
    },
    getUser(userId) {
      if (userId === this.handleUser.userId) {
        return this.handleUser
      } else if (userId === this.createdUser.userId) {
        return this.createdUser
      } else {
        return {}
      }
    },
    pageGetWorkOrderChat() {
      pageGetWorkOrderChat({
        workOrderId: this.workOrderId,
        pageSize: 10,
        currentPage: this.currentPage
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          for (const item of data.data) {
            const user = this.getUser(item.userId)
            const a = {
              'date': formatDate(this, item.createdDate),
              'text': { 'text': item.msg },
              'name': user.userName,
              'img': user.iconUrl
            }
            a.mine = this.userId === user.userId
            this.list.unshift(a)
          }
        }
      })
    },
    bindEnter(e) {
      const msg = this.inputMsg
      if (!msg) return
      this.insertWorkOrderChat(msg)
    },
    insertWorkOrderChat(msg) {
      insertWorkOrderChat({
        workOrderId: this.workOrderId,
        msg: msg
      })
    }
  }
}
</script>

